package com.adee.java;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test025_CountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        test1();
    }

    /*
    * CountDownLatch表示计数器，可以给CountDownLatch设置一个数字，一个线程调用CountDownLatch的await()将会阻塞，其他线程
    * 可以调用countDown()方法来对计数器减1，当计数器减为0后，所有await的线程都会被唤醒。
    * 对应的底层原理就是，调用await()方法的线程会利用AQS排队，一旦数字被减为0，则会将AQS中排队的线程依次唤醒。
    * */
    public static void test1() throws InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 3; i++) {
            threadPool.submit(() -> {
                for (;;) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(countDownLatch.getCount() == 0) break;
                    System.out.println("counting down...");
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("done");
    }
}
